package com.jason.learn.springcloud.orderservice.service;

import com.jason.learn.springcloud.orderservice.enty.BuyOrder;
import com.jason.learn.springcloud.orderservice.enty.constants.OrderStatus;
import com.jason.learn.springcloud.orderservice.dao.OrderDao;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Calendar;

@Service
public class OrderService {
    private Logger logger = LoggerFactory.getLogger(OrderService.class);
    @Autowired
    private OrderDao orderDao;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;



    /**
     * 模拟需要执行三个事务
     *      一、修改订单状态
     *      二、给inAccountId增加amount
     *      三、给outAccountId减少amount
     */
    public boolean orderPayFlow(Long orderId,Long inAccountId){
        logger.info("发起订单支付流程");
        BuyOrder order = orderDao.findById(orderId);
        String msg1 = inAccountId+","+order.getAmount();

        //setHeader"keys" -> keys
        Message<String> sendMsg1 = MessageBuilder.withPayload(msg1).setHeader("KEYS",orderId+"add").build();
         //orderPayFlow:add  ->  topic:tag
        logger.info("发送消息"+sendMsg1.getPayload());
        SendResult result1 = rocketMQTemplate.sendMessageInTransaction("orderTxProducerGroup","orderPayFlow:add",sendMsg1,order);
       logger.info("发送完毕");
        return SendStatus.SEND_OK.equals(result1.getSendStatus()) ;
    }

    public Long createOrder(Long merNo, BigDecimal amount,String buyerCard){
        BuyOrder order = new BuyOrder();
        order.setMerNo(merNo);
        order.setAmount(amount);
        order.setStatus(OrderStatus.CREATED);
        order.setCreateTime(Calendar.getInstance().getTime());
        order.setBuyerCard(buyerCard);
        orderDao.addOne(order);
        return order.getOrderId();
    }
}
